package com.lcz.ssm.controller;

import com.alibaba.druid.util.StringUtils;
import com.lcz.ssm.model.IsLogin;
import com.lcz.ssm.model.LoginForm;
import com.lcz.ssm.model.User;
import com.lcz.ssm.service.UserService;
import com.lcz.ssm.utils.AjaxResponse;
import com.lcz.ssm.utils.IdGen;
import com.lcz.ssm.utils.Md5Encoder;
import com.lcz.ssm.utils.ResponseEnum;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by LuChunzhou on 2016/7/15.
 */

@Controller
@RequestMapping("/login")
public class LoginController extends BaseController{

    private Logger log = Logger.getLogger(LoginController.class);
    @Autowired
    private UserService userService;

    /**
     * 跳转到登录界面
     * @return
     */
    @RequestMapping(value = "/loginView", method = RequestMethod.GET)
    public String loginView(){
        System.out.print("1");
        return "login";
    }

    /**
     * 用户登录
     * @param loginUser
     * @return
     */
    @RequestMapping(value="/login",method=RequestMethod.POST)
    public String login(User loginUser, HttpSession httpSession){
        User user;
        if(loginUser == null
        || "".equals(loginUser.getUserName())
        || null == loginUser.getUserName()
        || "".equals(loginUser.getUserPwd())
        || null == loginUser.getUserPwd()){
            return "login";
        }
        String password = Md5Encoder.generateCode(loginUser.getUserPwd());
        loginUser.setUserPwd(password);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userName",loginUser.getUserName());
        params.put("userPwd",loginUser.getUserPwd());
        try {
            user = userService.queryUserByLoginNamePasswordMap(params);
        } catch (RuntimeException e) {
            log.error("登陆错误："+e.getMessage(), e);
            throw new RuntimeException(e.getMessage(), e);
        }
        if(user!=null){
            loginUser.setUserPwd("");
            httpSession.setAttribute("loginUser",loginUser);
            return "redirect:/user/showUser";
        }else{
            return "login";
        }
    }
//    /**
//     * 登录
//     *
//     * @return ModelAndView
//     * @author 杜茂华
//     */
//    @RequestMapping(value = "/admin/session", method = RequestMethod.POST)
//    public ModelAndView login(@Valid @RequestBody LoginForm loginForm, BindingResult br, HttpServletRequest request) {
//        AjaxResponse ajaxResponse = super.buildAjaxResponse(request);
//        IsLogin isLogin = new IsLogin();
//        //服务器端验证
//        if (br.hasErrors()) {
//            return super.loginOutView(request);
//        }
////        ModelAndView mav = new ModelAndView();
//        Subject currentUser = SecurityUtils.getSubject();
//        Session session = currentUser.getSession();
//        UsernamePasswordToken token = new UsernamePasswordToken(loginForm.getUsername(),loginForm.getPassword());
//        token.setRememberMe(true);
//        try {
//            currentUser.login(token);
//        } catch (UnknownSessionException use) {
//            currentUser = new Subject.Builder().buildSubject();
//            currentUser.login(token);
//            session = currentUser.getSession(true);
//        }catch (AuthenticationException e) {
//            isLogin.setIsLogin(false);
//            ajaxResponse.addModelObject(isLogin);
//            ajaxResponse.setStat(ResponseEnum.ERROR);
//            ajaxResponse.setSilent(true);
////            e.printStackTrace();
//            return ajaxResponse.getMav();
//        }
//        if(currentUser.isAuthenticated()){
//            Map<String,Object> params = new HashMap<String, Object>();
//            params.put("loginName",loginForm.getUsername());
//            params.put("password", Md5Encoder.generateCode(loginForm.getPassword()));
//            User user = userService.queryUserByLoginNamePasswordMap(params);
//            isLogin.setIsLogin(false);
//            ajaxResponse.setStat(ResponseEnum.ERROR);
//            ajaxResponse.setSilent(true);
//            ajaxResponse.addModelObject(isLogin);
//            isLogin.setImage(user.getImage());
//            //组装图片压缩的长宽 end -----------------------------
//            session.setAttribute("user", user);
//            isLogin.setIsLogin(true);
//            ajaxResponse.addModelObject(isLogin);
//            return ajaxResponse.getMav();
//        }else{
//            isLogin.setIsLogin(false);
//            ajaxResponse.setStat(ResponseEnum.ERROR);
//            ajaxResponse.setSilent(true);
//            ajaxResponse.addModelObject(isLogin);
//            return ajaxResponse.getMav();
//        }
//    }

    /**
     * 跳转到注界面
     * @return
     */
    @RequestMapping(value="/registerView",method=RequestMethod.GET)
    public String toRegister(){
        return "register";
    }

    /**
     * 注册
     * @param regUser
     * @return
     */
    @RequestMapping(value="/register",method=RequestMethod.POST)
    public ModelAndView register(User regUser){
        ModelAndView mov = new ModelAndView();
        if(regUser == null
        || "".equals(regUser.getUserName())
        || null == regUser.getUserName()
        || "".equals(regUser.getUserPwd())
        || null == regUser.getUserPwd()){
            mov.setViewName("register");
            return mov;
        }
        List<User> userList = userService.getAllUser();
        if(userList.size()>0){
            for(User each : userList){
                if(each.getUserName().equals(regUser.getUserName())){
                    //返回这里的逻辑可能有问题，break不知道怎么加。
                    mov.setViewName("register");
                    return mov;
                }
            }
        }
        regUser.setId(IdGen.uuid());
        regUser.setPwdSalt("121");
        regUser.setCreatedInfors();
        String password = Md5Encoder.generateCode(regUser.getUserPwd());
        regUser.setUserPwd(password);
        userService.regUser(regUser);
        mov.setViewName("login");
        mov.addObject("regUser",regUser);
        return mov;
    }

    /**
     * 用户登出
     * @param httpSession
     * @return
     */
    @RequestMapping(value="/loginOut",method=RequestMethod.GET)
    public String loginOut(HttpSession httpSession){
        httpSession.invalidate();
        return "login";
    }

//    /**
//     * 忘记密码，发送邮件到用户邮箱进行验证
//     * @param request
//     * @param userName
//     * @return
//     */
//    @RequestMapping(value = "/user/i_forget_password")
//    @ResponseBody
//    public Map forgetPass(HttpServletRequest request, String userName){
//        User users = userService.queryUserByName(userName);
//        Map map = new HashMap<String ,String >();
//        String msg = "";
//        if(users == null){              //用户名不存在
//            msg = "用户名不存在,你不会忘记用户名了吧?";
//            map.put("msg",msg);
//            return map;
//        }
//        try{
//            String secretKey= UUID.randomUUID().toString();  //密钥
//            Timestamp outDate = new Timestamp(System.currentTimeMillis()+10*60*1000);//10分钟后过期
//            long date = outDate.getTime()/1000*1000;                  //忽略毫秒数
//            users.setPwdSalt(secretKey);
//            users.setModifiedDate(outDate);
//            userService.updateUser(users);    //保存到数据库
//            String key = users.getUserName()+"$"+date+"$"+secretKey;
//            String digitalSignature = Md5Encoder.generateCode(key);                 //数字签名
//
//            String emailTitle = "密码找回";
//            String path = request.getContextPath();
//            String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
//            String resetPassHref =  basePath+"user/reset_password?sid="+digitalSignature+"&userName="+users.getUserName();
//            String emailContent = "请勿回复本邮件.点击下面的链接,重设密码<br/><a href="+resetPassHref +" target='_BLANK'>点击我重新设置密码</a>" +
//                    "<br/>tips:本邮件超过30分钟,链接将会失效，需要重新申请'找回密码'"+key+"\t"+digitalSignature;
//            System.out.print(resetPassHref);
//            SendMail.getInstance().sendHtmlMail(emailTitle,emailContent,users.getEmail());
//            msg = "操作成功,已经发送找回密码链接到您邮箱。请在30分钟内重置密码";
//            log.info(request+userName+"申请找回密码");
//        }catch (Exception e){
//            e.printStackTrace();
//            msg="邮箱不存在？未知错误,联系管理员吧。";
//        }
//        map.put("msg",msg);
//        return map;
//    }
//
//    /**
//     * 点击邮箱验证的方法
//     * @param sid
//     * @param userName
//     * @return
//     */
//    @RequestMapping(value = "/user/reset_password",method = RequestMethod.GET)
//    public ModelAndView checkResetLink(String sid,String userName){
//        ModelAndView model = new ModelAndView("error");
//        String msg = "";
//        if(sid.equals("") || userName.equals("")){
//            msg="链接不完整,请重新生成";
//            model.addObject("msg",msg) ;
//            log.info(userName+"找回密码链接失效");
//            return model;
//        }
//        User users = userService.queryUserByName(userName);
//        if(users == null){
//            msg = "链接错误,无法找到匹配用户,请重新申请找回密码.";
//            model.addObject("msg",msg) ;
//            log.info(userName+"找回密码链接失效");
//            return model;
//        }
//        Date outDate = users.getModifiedDate();
//        if(outDate.getTime() <= System.currentTimeMillis()){         //表示已经过期
//            msg = "链接已经过期,请重新申请找回密码.";
//            model.addObject("msg",msg) ;
//            log.info(userName+"找回密码链接失效");
//            return model;
//        }
//        String key = users.getUserName()+"$"+outDate.getTime()/1000*1000+"$"+users.getPwdSalt();          //数字签名
//        String digitalSignature = Md5Encoder.generateCode(key);
//        System.out.println(key+"\t"+digitalSignature);
//        if(!digitalSignature.equals(sid)) {
//            msg = "链接不正确,是否已经过期了?重新申请吧";
//            model.addObject("msg",msg) ;
//            log.info(userName+"找回密码链接失效");
//            return model;
//        }
//        model.setViewName("user/reset_password");  //返回到修改密码的界面
//        model.addObject("userName",userName);
//        return model;
//    }

}
